package com.itheima.controller.backend.Controller;

import com.itheima.DTO.OrderSettingDTO;
import com.itheima.VO.OrderSettingVO;
import com.itheima.common.entity.Result;
import com.itheima.controller.backend.Service.OrderSettingService;
import com.itheima.pojo.OrderSetting;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.List;

@RestController
@RequestMapping("/ordersetting")
@Slf4j
@Api(tags ="预约设置相关接口")
public class OrderSettingController {

    @Autowired
    private OrderSettingService orderSettingService;

    @GetMapping("/download")
    @ApiOperation("下载预约设置数据")
    //TODO
    public void download(HttpServletResponse response) {
        try {
            log.info("开始下载预约设置模板");
//            FileOutputStream in = new FileOutputStream(new File("D:/JavaCode/bxg-health-parent/bxg-health-backend/src/main/resources/templates/ordersetting_template.xlsx"));
//            InputStream in = this.getClass().getClassLoader().getResourceAsStream("templates/ordersetting_template.xlsx");

            XSSFWorkbook excel = new XSSFWorkbook();

            XSSFSheet sheet = excel.createSheet("预约设置模板");
            XSSFRow row = sheet.createRow(0);
            XSSFCell cell = row.createCell(0);
            cell.setCellValue("日期");

            cell = row.createCell(1);
            cell.setCellValue("可预约数量");

//            sheet.createRow(0).createCell(1).setCellValue("可预约数量");
//            int lastRowNum = sheet.getLastRowNum();
//            for (int i = 0; i < lastRowNum; i++) {
//                sheet.getRow(i+1).getCell(0).getStringCellValue();
//                sheet.getRow(i+1).getCell(1).getStringCellValue();
//            }

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=ordersetting_template.xlsx");


            ServletOutputStream out = response.getOutputStream();
            excel.write(out);


//            in.close();
            out.close();
            excel.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @PostMapping("/editNumberByOrderDate")
    @ApiOperation("根据日期修改可预约人数")
    public Result editNumberByOrderDate(@RequestBody OrderSettingDTO orderSettingDTO){
        log.info("根据日期修改可预约人数：{}",orderSettingDTO);
        orderSettingService.editNumberByOrderDate(orderSettingDTO);
        return new Result(true,"预约设置成功");
    }

    @GetMapping("/getOrderSettingByMonth")
    @ApiOperation("根据年月查询对应的预约设置信息")
    public Result getOrderSettingByMonth(@RequestParam("month") String month){
        log.info("根据年月查询对应的预约设置信息：{}",month);
        List<OrderSettingVO> list = orderSettingService.getOrderSettingByMonth(month);
        return new Result(true,"查询成功",list);
    }

    @PostMapping("/upload")
    @ApiOperation("文件上传（Excel）")
    public Result upload(@RequestParam("excelFile") MultipartFile excelFile) throws IOException {
        try {
            log.info("文件上传（Excel）");
            InputStream in = excelFile.getInputStream();
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("预约设置模板");
            int lastRowNum = sheet.getLastRowNum();
            for (int i = 0; i < lastRowNum; i++) {
                XSSFRow row = sheet.getRow(i + 1);
                XSSFCell cell = row.getCell(0);
//                String date = getCellValueAsString(cell);
                java.util.Date date = cell.getDateCellValue();
                cell = row.getCell(1);
                int number = (int) getCellValueAsNumeric(cell);


                OrderSetting orderSetting = new OrderSetting();

                orderSetting.setOrderDate(date);
                orderSetting.setNumber(number);
//                把数据写进模板里，下次下载模板的时候可以看到，但好像没必要了！！！
//                OutputStream out = new FileOutputStream(new File("D:/JavaCode/bxg-health-parent/bxg-health-backend/src/main/resources/templates/ordersetting_template.xlsx"));
//                excel.write(out);
//                out.close();
                OrderSettingDTO orderSettingDTO = new OrderSettingDTO();
                orderSettingDTO.setOrderDate(date);
                orderSettingDTO.setNumber(number);
                orderSettingService.Insert(orderSettingDTO);
            }
            in.close();
            excel.close();
            return new Result(true,"文件上传成功");
        }
        catch (Exception e){
            e.printStackTrace();
            return new Result(false,"文件上传失败");
        }
    }

    private static String getCellValueAsString(XSSFCell cell) {
        if (cell == null) return null;
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return String.valueOf(cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return null;
        }
    }

    private static double getCellValueAsNumeric(XSSFCell cell) {
        if (cell == null) return 0.0;
        switch (cell.getCellType()) {
            case NUMERIC:
                return cell.getNumericCellValue();
            case STRING:
                try {
                    return Double.parseDouble(cell.getStringCellValue());
                } catch (NumberFormatException e) {
                    return 0.0;
                }
            default:
                return 0.0;
        }
    }

}
